package com.aiyige.page.authentication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.request.SubmitOrganizationCertificationRequest;
import com.aiyige.page.authentication.model.Authentication;
import com.aiyige.utils.DialogUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UploadPhotoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.RoundCornerImageView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.OrganizationAuthenticationPage)
public class OrganizationAuthenticationPage extends AppCompatActivity {
    public static final int REQUEST_CODE_BUSINESS_LICENSE = 1;
    public static final int REQUEST_CODE_ID_CARD_FRONT = 2;
    public static final int REQUEST_CODE_ID_CARD_BACK = 3;
    public static final int NEXT = 4;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    TextView titleActionBtn;
    @BindView(R.id.companyNameLabel)
    TextView companyNameLabel;
    @BindView(R.id.companyNameEt)
    EditText companyNameEt;
    @BindView(R.id.legalPersonNameLabel)
    TextView legalPersonNameLabel;
    @BindView(R.id.legalPersonNameEt)
    EditText legalPersonNameEt;
    @BindView(R.id.idNumLabel)
    TextView idNumLabel;
    @BindView(R.id.idNumEt)
    EditText idNumEt;
    @BindView(R.id.businessLicenseBgIv)
    ImageView businessLicenseBgIv;
    @BindView(R.id.businessLicenseTv)
    TextView businessLicenseTv;
    @BindView(R.id.businessLicenseIv)
    RoundCornerImageView businessLicenseIv;
    @BindView(R.id.businessLicenseDeleteIv)
    ImageView businessLicenseDeleteIv;
    @BindView(R.id.businessLicenseLayout)
    ConstraintLayout businessLicenseLayout;
    @BindView(R.id.idCardFrontBgIv)
    ImageView idCardFrontBgIv;
    @BindView(R.id.idCardFrontIv)
    RoundCornerImageView idCardFrontIv;
    @BindView(R.id.idCardFrontDeleteIv)
    ImageView idCardFrontDeleteIv;
    @BindView(R.id.idCardFrontTv)
    TextView idCardFrontTv;
    @BindView(R.id.idCardFrontLayout)
    ConstraintLayout idCardFrontLayout;
    @BindView(R.id.idCardBackBgIv)
    ImageView idCardBackBgIv;
    @BindView(R.id.idCardBackIv)
    RoundCornerImageView idCardBackIv;
    @BindView(R.id.idCardBackDeleteIv)
    ImageView idCardBackDeleteIv;
    @BindView(R.id.idCardBackTv)
    TextView idCardBackTv;
    @BindView(R.id.idCardBackLayout)
    ConstraintLayout idCardBackLayout;
    @Autowired
    Authentication authentication = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.organization_authentication_page);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (authentication == null) {
            ToastX.show(R.string.unknown_error);
            finish();
            return;
        }

        companyNameEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                authentication.setCompanyName(s.toString());
            }
        });
        companyNameEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        legalPersonNameEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                authentication.setLegalPersonName(s.toString());
            }
        });
        legalPersonNameEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        idNumEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                authentication.setLegalPersonIdNum(s.toString());
            }
        });
        idNumEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        titleTv.setText(R.string.organization_user_authentication);
        updateView();
    }


    public void updateView() {
        companyNameEt.setText(authentication.getCompanyName());
        legalPersonNameEt.setText(authentication.getLegalPersonName());
        idNumEt.setText(authentication.getLegalPersonIdNum());
        if (authentication.isReadOnly()) {
            titleActionBtn.setText(R.string.reauthentication);
        } else {
            titleActionBtn.setText(R.string.submit_authentication);
        }
        if (TextUtils.isEmpty(authentication.getBusinessLicenseLocalUrl())
                && TextUtils.isEmpty(authentication.getBusinessLicenseRemoteUrl())) {
            businessLicenseIv.setVisibility(View.INVISIBLE);
            businessLicenseDeleteIv.setVisibility(View.INVISIBLE);
            businessLicenseBgIv.setVisibility(View.VISIBLE);
            businessLicenseTv.setVisibility(View.VISIBLE);
        } else {
            businessLicenseBgIv.setVisibility(View.INVISIBLE);
            businessLicenseTv.setVisibility(View.INVISIBLE);
            businessLicenseIv.setVisibility(View.VISIBLE);
            businessLicenseDeleteIv.setVisibility(authentication.isReadOnly() ? View.INVISIBLE : View.VISIBLE);
            String photoUrl = !TextUtils.isEmpty(authentication.getBusinessLicenseRemoteUrl()) ? authentication.getBusinessLicenseRemoteUrl() : authentication.getBusinessLicenseLocalUrl();
            Glide.with(this).asBitmap().load(photoUrl)
                    .apply(RequestOptions.placeholderOf(R.color.transparent))
                    .into(businessLicenseIv);
        }


        if (TextUtils.isEmpty(authentication.getLegalPersonIdCardFrontLocalUrl())
                && TextUtils.isEmpty(authentication.getLegalPersonIdCardFrontRemoteUrl())) {
            idCardFrontIv.setVisibility(View.INVISIBLE);
            idCardFrontDeleteIv.setVisibility(View.INVISIBLE);
            idCardFrontBgIv.setVisibility(View.VISIBLE);
            idCardFrontTv.setVisibility(View.VISIBLE);
        } else {
            idCardFrontBgIv.setVisibility(View.INVISIBLE);
            idCardFrontTv.setVisibility(View.INVISIBLE);
            idCardFrontIv.setVisibility(View.VISIBLE);
            idCardFrontDeleteIv.setVisibility(authentication.isReadOnly() ? View.INVISIBLE : View.VISIBLE);
            String photoUrl = !TextUtils.isEmpty(authentication.getLegalPersonIdCardFrontRemoteUrl()) ? authentication.getLegalPersonIdCardFrontRemoteUrl() : authentication.getLegalPersonIdCardFrontLocalUrl();
            Glide.with(this).asBitmap().load(photoUrl)
                    .apply(RequestOptions.placeholderOf(R.color.transparent))
                    .into(idCardFrontIv);
        }

        if (TextUtils.isEmpty(authentication.getLegalPersonIdCardBackLocalUrl())
                && TextUtils.isEmpty(authentication.getLegalPersonIdCardBackRemoteUrl())) {
            idCardBackIv.setVisibility(View.INVISIBLE);
            idCardBackDeleteIv.setVisibility(View.INVISIBLE);
            idCardBackBgIv.setVisibility(View.VISIBLE);
            idCardBackTv.setVisibility(View.VISIBLE);
        } else {
            idCardBackBgIv.setVisibility(View.INVISIBLE);
            idCardBackTv.setVisibility(View.INVISIBLE);
            idCardBackIv.setVisibility(View.VISIBLE);
            idCardBackDeleteIv.setVisibility(authentication.isReadOnly() ? View.INVISIBLE : View.VISIBLE);
            String photoUrl = !TextUtils.isEmpty(authentication.getLegalPersonIdCardBackRemoteUrl()) ? authentication.getLegalPersonIdCardBackRemoteUrl() : authentication.getLegalPersonIdCardBackLocalUrl();
            Glide.with(this).asBitmap()
                    .apply(RequestOptions.placeholderOf(R.color.transparent))
                    .load(photoUrl).into(idCardBackIv);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case NEXT:
                setResult(RESULT_OK);
                finish();
                break;
            case REQUEST_CODE_BUSINESS_LICENSE:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = ListUtil.getFirstItem(selectList);
                    if (localMedia != null) {
                        authentication.setBusinessLicenseLocalUrl(localMedia.getPath());
                        authentication.setBusinessLicenseRemoteUrl("");
                        updateView();
                        UploadPhotoUtil.newBuilder()
                                .photoLocalUrl(authentication.getBusinessLicenseLocalUrl())
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(OrganizationAuthenticationPage.this)
                                                .message(R.string.uploading)
                                                .cancelable(false)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {

                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        loadingDialog.dismiss();
                                        ToastX.show(R.string.upload_failed);
                                        authentication.setBusinessLicenseRemoteUrl("");
                                        authentication.setBusinessLicenseLocalUrl("");
                                        updateView();
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        loadingDialog.dismiss();
                                        authentication.setBusinessLicenseRemoteUrl(url);
                                    }
                                })
                                .build()
                                .upload();
                    }

                }
                break;
            case REQUEST_CODE_ID_CARD_FRONT:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = ListUtil.getFirstItem(selectList);
                    if (localMedia != null) {
                        authentication.setLegalPersonIdCardFrontLocalUrl(localMedia.getPath());
                        authentication.setLegalPersonIdCardFrontRemoteUrl("");
                        updateView();
                        UploadPhotoUtil.newBuilder()
                                .photoLocalUrl(authentication.getLegalPersonIdCardFrontLocalUrl())
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(OrganizationAuthenticationPage.this)
                                                .message(R.string.uploading)
                                                .cancelable(false)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {

                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        loadingDialog.dismiss();
                                        ToastX.show(R.string.upload_failed);
                                        authentication.setLegalPersonIdCardFrontRemoteUrl("");
                                        authentication.setLegalPersonIdCardFrontLocalUrl("");
                                        updateView();
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        loadingDialog.dismiss();
                                        authentication.setLegalPersonIdCardFrontRemoteUrl(url);
                                    }
                                })
                                .build()
                                .upload();
                    }
                }
                break;
            case REQUEST_CODE_ID_CARD_BACK:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = ListUtil.getFirstItem(selectList);
                    if (localMedia != null) {
                        authentication.setLegalPersonIdCardBackLocalUrl(localMedia.getPath());
                        authentication.setLegalPersonIdCardBackRemoteUrl("");
                        updateView();
                        UploadPhotoUtil.newBuilder()
                                .photoLocalUrl(authentication.getLegalPersonIdCardBackLocalUrl())
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(OrganizationAuthenticationPage.this)
                                                .message(R.string.uploading)
                                                .cancelable(false)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {

                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        loadingDialog.dismiss();
                                        ToastX.show(R.string.upload_failed);
                                        authentication.setLegalPersonIdCardBackRemoteUrl("");
                                        authentication.setLegalPersonIdCardBackLocalUrl("");
                                        updateView();
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        loadingDialog.dismiss();
                                        authentication.setLegalPersonIdCardBackRemoteUrl(url);
                                    }
                                })
                                .build()
                                .upload();
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        DialogUtil.makeConfirmExitDialog(this, R.string.confirm_exit_edit, R.string.abandon, R.string.cancel).show();
    }

    public boolean checkFormValidate() {
        boolean result = true;
        if (TextUtils.isEmpty(authentication.getCompanyName())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getLegalPersonName())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getLegalPersonIdNum())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getBusinessLicenseRemoteUrl())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getLegalPersonIdCardFrontRemoteUrl())) {
            result = false;
        }
        if (TextUtils.isEmpty(authentication.getLegalPersonIdCardBackRemoteUrl())) {
            result = false;
        }
        return result;
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn, R.id.businessLicenseBgIv, R.id.businessLicenseDeleteIv, R.id.idCardFrontBgIv, R.id.idCardFrontDeleteIv, R.id.idCardBackBgIv, R.id.idCardBackDeleteIv})
    public void onViewClicked(View view) {
        companyNameEt.clearFocus();
        legalPersonNameEt.clearFocus();
        idNumEt.clearFocus();
        switch (view.getId()) {
            case R.id.titleBackBtn:
                DialogUtil.makeConfirmExitDialog(this, R.string.confirm_exit_authentication, R.string.confirm, R.string.cancel).show();
                break;
            case R.id.titleActionBtn:
                if (authentication.isReadOnly()) {
                    authentication = Authentication.newBuilder()
                            .userType(Authentication.USER_TYPE_ORGANIZATION)
                            .readOnly(false)
                            .build();
                    updateView();
                } else if (checkFormValidate()) {
                    doSubmit();
                }
                break;
            case R.id.businessLicenseBgIv:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .isGif(false)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_BUSINESS_LICENSE);
                break;
            case R.id.businessLicenseDeleteIv:
                authentication.setBusinessLicenseLocalUrl("");
                authentication.setBusinessLicenseRemoteUrl("");
                updateView();
                break;
            case R.id.idCardFrontBgIv:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .isGif(false)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_ID_CARD_FRONT);
                break;
            case R.id.idCardFrontDeleteIv:
                authentication.setLegalPersonIdCardFrontLocalUrl("");
                authentication.setLegalPersonIdCardFrontRemoteUrl("");
                updateView();
                break;
            case R.id.idCardBackBgIv:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .isGif(false)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_ID_CARD_BACK);
                break;
            case R.id.idCardBackDeleteIv:
                authentication.setLegalPersonIdCardBackLocalUrl("");
                authentication.setLegalPersonIdCardBackRemoteUrl("");
                updateView();
                break;
        }
    }

    public void doSubmit() {
        new SubmitTask(this).execute();
    }

    public class SubmitTask extends SafeAsyncTask<Object, Object, Object> {

        public SubmitTask(Activity activity) {
            super(activity, R.string.text_process);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                ARouter.getInstance()
                        .build(ARouterConfig.WaitingAuthenticationPage)
                        .navigation(OrganizationAuthenticationPage.this, NEXT);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().submitOrganizationCertification(SubmitOrganizationCertificationRequest.newBuilder()
                        .businessLicenseUrl(authentication.getBusinessLicenseRemoteUrl())
                        .companyName(authentication.getCompanyName())
                        .IDCardBackUrl(authentication.getLegalPersonIdCardBackRemoteUrl())
                        .IDCardFrontUrl(authentication.getLegalPersonIdCardFrontRemoteUrl())
                        .IDCardName(authentication.getLegalPersonName())
                        .IDCardNo(authentication.getLegalPersonIdNum())
                        .build()).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }
}
